package com.yjt.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * @author 曾智平
 * @ClassName: FileUtil
 * @Description: 文件工具类
 * @date 2021/10/14 14:49
 */
public class FileUtil {
    /**
     * 文件单位
     */
    public static final String B_UNIT = "B";
    public static final String K_UNIT = "K";
    public static final String M_UNIT = "M";
    public static final String G_UNIT = "G";

    /**
     * 图片类型 jpg、jpeg、png
     */
    public static String[] IMAGE_TYPE = {"jpg", "png", "jpeg"};

    /**
     * 判断文件是否超过限制
     *
     * @param len 文件长度
     * @param size 文件限制长度
     * @param unit 文件单位
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize;
        switch (unit.toUpperCase()) {
            case K_UNIT:
                fileSize = (double) len / 1024;
                break;
            case M_UNIT:
                fileSize = (double) len / 1048576;
                break;
            case G_UNIT:
                fileSize = (double) len / 1073741824;
                break;
            default:
                fileSize = (double) len;
                break;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     *  检查文件是否为图片类型
     * @param file
     * @return
     */
    public static boolean checkFileIsImage(MultipartFile file) {
        //文件名称
        String realFileName = file.getOriginalFilename();
        //文件后缀
        String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1);

        if (Arrays.asList(IMAGE_TYPE).contains(suffix)) {
            return true;
        }
        return false;
    }


}
